package com.example.project.projectspringcloud.controller.admin.sysconfig;

import com.example.project.projectspringcloud.common.Constants;
import com.example.project.projectspringcloud.common.OperationException;
import com.example.project.projectspringcloud.entity.Page;
import com.example.project.projectspringcloud.entity.RespBody;
import com.example.project.projectspringcloud.entity.sys.Dictionary;
import com.example.project.projectspringcloud.service.sys.SysDictionaryService;
import com.example.project.projectspringcloud.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "后台字典管理控制器")
@Controller
@RequestMapping(value = "/admin/dictionary")
public class AdminSysDictionaryController {

    @Autowired
    private SysDictionaryService dictionaryService;

    @ApiOperation(value = "管理列表", notes = "返回后台管理列表")
    @RequestMapping(value = {"", "/list"}, method = {RequestMethod.GET, RequestMethod.POST})
    public String list(Dictionary dictionary, Page page, Model model) {
        List<Dictionary> dictionaries = dictionaryService.list(dictionary, page);
        model.addAttribute("page", new Page<Dictionary>(dictionaries));
        model.addAttribute("dictionary", dictionary);
        return "admin/sysconfig/sys-dictionary-list";
    }

    @ApiOperation(value = "表单数据", notes = "返回表单数据")
    @GetMapping(value = "/form")
    public String form(@RequestParam(value = "id", required = false) Integer id, Model model) {
        if (id != null) {
            Dictionary dictionary = dictionaryService.get(new Dictionary(id));
            model.addAttribute("dictionary", dictionary);
        }
        return "admin/sysconfig/sys-dictionary-form";
    }

    @ApiOperation(value = "保存/更新", notes = "保存/更新")
    @PostMapping(value = "/api/save")
    @ResponseBody
    public RespBody save(Dictionary dictionary) {
        try {
            boolean result = dictionaryService.save(dictionary);
            if (!result) {
                return RespBody.error(Constants.Message.SAVE_FAILED);
            }
        } catch (OperationException e) {
            return RespBody.error(e.getMessage());
        }

        return RespBody.ok(Constants.Message.SAVE_SUCCESS);
    }

    @ApiOperation(value = "删除", notes = "删除")
    @DeleteMapping(value = "/api/delete/{ids}")
    @ResponseBody
    public RespBody delete(@ApiParam(value = "id/ids 1,2,3...") @PathVariable("ids") String ids) {
        boolean result = dictionaryService.delete(StringUtil.split(ids, ","));
        if (!result) {
            return RespBody.error(Constants.Message.SAVE_FAILED);
        }

        return RespBody.ok(Constants.Message.SAVE_SUCCESS);
    }
}
